﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace Devonline.AspNetCore;

/// <summary>
/// Http 请求拦截中间件
/// </summary>
public class HttpInterceptMiddleware(RequestDelegate next)
{
    private readonly RequestDelegate _next = next;

    /// <summary>
    /// 中间件执行方法
    /// </summary>
    /// <param name="context"></param>
    /// <param name="interceptor"></param>
    /// <param name="logger"></param>
    /// <returns></returns>
    public async Task InvokeAsync(HttpContext context, HttpInterceptor interceptor, ILogger<HttpInterceptMiddleware> logger)
    {
        var glabalInterceptor = interceptor[HTTP_REQUEST_INTERCEPT_GLOBAL];
        if (!string.IsNullOrWhiteSpace(glabalInterceptor))
        {
            logger.LogInformation("Global HTTP request intercept is active, the request will be intercepted");
            context.Response.StatusCode = StatusCodes.Status405MethodNotAllowed;
            context.Response.ContentType = DEFAULT_CONTENT_TYPE;
            await context.Response.WriteAsync($"{glabalInterceptor} 正在进行中, 此时不能发起任何请求, 请等待任务完成!");
            return;
        }

        var keyIntercept = context.Request.GetFromRequest<string>(HTTP_REQUEST_INTERCEPT_KEY);
        if (!string.IsNullOrWhiteSpace(keyIntercept))
        {
            var interceptorValue = interceptor[keyIntercept];
            if (!string.IsNullOrWhiteSpace(interceptorValue))
            {
                logger.LogInformation($"HTTP request intercept key: {keyIntercept} is active, the current request will be intercepted");
                context.Response.StatusCode = StatusCodes.Status405MethodNotAllowed;
                context.Response.ContentType = DEFAULT_CONTENT_TYPE;
                await context.Response.WriteAsync($"{interceptorValue} 正在进行中, 此时不能发起当前请求, 请等待任务完成!");
                return;
            }
        }

        // Call the next delegate/middleware in the pipeline.
        await _next(context);
    }
}